import Vue from 'vue'
import VueRouter from "vue-router";
Vue.use(VueRouter)

//重写push方法，解决相同路由多次点击出现异常
const originalPush = VueRouter.prototype.push
// 重写了原型上的push方法，统一的处理了错误信息
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


// let routers = require.context('views', true).keys()
// const modulesFiles =  require.context('../views', true).keys() 
// console.log(modulesFiles);
// 配置路由规则，设置路由懒加载
// 方式一
let routes;

routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import( /* webpackChunkName: "group-foo" */ "@/views/login/login.vue"),
    meta: {
      layout: 'login',
      //使用keep-alive缓存路由组件
      keepAlive: false
    }
  }, {
    path: '/',    
    redirect: '/login',
    meta: {
      layout: 'login'
    }
  }, {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "group-foo" */ "@/views/page/home.vue"),
    meta: {
      layout: 'default'
    }
  },
  , {
    path: '/home1',
    name: 'home1',
    component: () => import(/* webpackChunkName: "group-foo" */ "@/views/page/home1.vue"),
    meta: {
      layout: 'default'
    }
  },
  {
    name: '404',
    path: '/404',
    meta: {
      layout: 'login'
    },
    component: () => import('@/views/error/404.vue')
  },
  {
    path: '*', 
    redirect: '/404',
    meta: {
      layout: 'login'
    }
  }

];






// 方式二 webpack提供的require.ensure()

// const routes=[
// {
//   path: '/login',
//   name: 'login',
//   component: r => require.ensure([], () => r(require('@/views/login/login.vue')), 'demo')
// }, {
//   path: '/de',
//   name: 'home',
//   component: r => require.ensure([], () => r(require('@/views/home/home.vue')), 'demo')
// }
// ]
// 方式三
// const routes=[
//   ,{
//     path: '/login',
//     name: 'login',
//     component: resolve => require(['@/views/login/login.vue'],resolve)
//   },{
//   path: '/de',
//   name: 'home',
//   component: resolve => require(['@/views/home/home.vue'],resolve)
// } ]
const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => { 
  const isLogin = localStorage.getItem("login")
  if(isLogin && to.name =='login'){
    next();
  }else if(!isLogin && to.name!= 'login'){
    next({name:"login"});
  }else{
    next()
  }
});
// router.beforeResolve((to, from, next) => {
//   next();
// });
// router.afterEach((to, from) => {
//   console.log('afterEach 全局后置钩子');
// });

export default router
